package com.car.action.api;

import java.math.BigDecimal;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.car.backend.opensource.AlipayConfig;
import com.car.backend.opensource.WeiXinAPPUtil;
import com.car.common.model.Users;
import com.car.common.model.VipPackage;
import com.car.common.model.VipRecord;
import com.jfinal.core.Controller;
import com.utils.CommonUtil;
import com.utils.CookiesUtil;
import com.utils.GetWxOrderno;
import com.utils.Sha1Util;
import com.utils.StringUtil;
import com.utils.SystemClock;
import com.utils.TenpayUtil;
import com.utils.Toolkit;
import com.utils.WeiXinUtil;

public class WeiXinController extends Controller{
	
	public void vip_user(){
		setAttr("user_name", CookiesUtil.getName(getRequest(), "user_name"));
		List<VipPackage> package_list = VipPackage.dao.find("select * from vip_package where status = 1  order by id desc ");
		setAttr("package_list", package_list);
	    render("vip.html");
		/*
		try {
			String code = getPara("code");
		    if(!StringUtil.empty(code)){
		          String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WeiXinUtil.appid+"&secret="+WeiXinUtil.appsecret+"&code="+code+"&grant_type=authorization_code";
		          net.sf.json.JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
//		          System.out.println(jsonObject);
		          if (null != jsonObject) {
		              String openId = jsonObject.getString("openid");
		              CookiesUtil.add(getResponse(), "wx_openid", openId);
		              String access_token = jsonObject.getString("access_token");
		              String URL2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" +access_token+ "&openid="+openId+ "&lang=zh_CN";
		              net.sf.json.JSONObject myJsonObject1 = CommonUtil.httpsRequest(URL2, "GET", null);
//		              System.out.println(myJsonObject1);
		          } 
		          setAttr("user_name", CookiesUtil.getName(getRequest(), "user_name"));
		          List<VipPackage> package_list = VipPackage.dao.find("select * from vip_package where status = 1  order by type, id desc ");
		          setAttr("package_list", package_list);
				  render("vip.html");
		    } else {
	              String redirect_uri ="http://wx.50dufei.top/pay/vip_user";
	              String scope = "snsapi_userinfo";
	              String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WeiXinUtil.appid +"&redirect_uri="+redirect_uri +"&response_type=code&scope="+scope+"&state=wx#wechat_redirect";
	              redirect(url);
		    }
		 }catch (Exception e){
             e.printStackTrace();
         }
		 */
	 }
	
	public void package_list() {
//		System.out.println(CookiesUtil.getName(getRequest(), "wx_openid"));
		if (StringUtil.empty(CookiesUtil.getName(getRequest(), "wx_openid"))) {
			vip_user();
		} else {
			List<VipPackage> package_list = VipPackage.dao.find("select * from vip_package where status = 1  order by type, id desc ");
			setAttr("package_list", package_list);
			setAttr("user_name", CookiesUtil.getName(getRequest(), "user_name"));
		    render("vip.html");
		}
	}
	
	public void wx() {
		setAttr("user_name", CookiesUtil.getName(getRequest(), "user_name"));
		List<VipPackage> package_list = VipPackage.dao.find("select * from vip_package where status = 1  order by id desc ");
		setAttr("package_list", package_list);
	    render("vip.html");
	}
	
	public void vip2() {
		setAttr("user_name", CookiesUtil.getName(getRequest(), "user_name"));
		List<VipPackage> package_list = VipPackage.dao.find("select * from vip_package where status = 1  order by id desc ");
		setAttr("package_list", package_list);
	    render("vip2.html");
	}
	
	public void vip_alipay() {
		CookiesUtil.add(getResponse(), "user_name", getPara("user_name"));
		setAttr("user_name", CookiesUtil.getName(getRequest(), "user_name"));
		List<VipPackage> package_list = VipPackage.dao.find("select * from vip_package where status = 1  order by id desc ");
		setAttr("package_list", package_list);
	    render("vip_alipay.html");
	}
	
	public void vip() {
		String user_name = getPara("user_name");
		Users users = Users.dao.findFirst("select id from users where user_mobile ='" + user_name + "'");
	    if( users == null){
	    	Long user_id = getParaToLong("user_name") - 20000000L;
	    	users = Users.dao.findById(user_id);
	    }
	    CookiesUtil.add(getResponse(), "user_name", user_name);
	    Long user_id = users.getId();
		String package_id = getPara("package_id");
		VipPackage vipPackage = VipPackage.dao.findById(package_id);
		String trade_no = Toolkit.newTradeNo();
		BigDecimal price =new BigDecimal(0);
		if (vipPackage != null) {
			if (vipPackage.getType() == 1) {
				VipRecord one = new VipRecord();
				one.setUserId(user_id.intValue());
				one.setOrderNum(trade_no);
				one.setTitle(vipPackage.getTitle());
				one.setBuyType("User");
				one.setZsHot(vipPackage.getZsHot());
				one.setTime(Integer.valueOf(vipPackage.getDays()));
				one.setPrice(vipPackage.getPrice());
				price = vipPackage.getPrice();
				one.setStatus(2);
				one.setOrderType(1);
				one.setVipPackageId(vipPackage.getId());
				one.setCreateTime(SystemClock.now()/1000L);
				one.setUpdateTime(SystemClock.now()/1000L);
				if (user_id.longValue() == 140901L) {
					one.setPrice(new BigDecimal(0.01));
				}
				one.save();
			} else {
				VipRecord one = new VipRecord();
				one.setUserId(user_id.intValue());
				one.setOrderNum(trade_no);
				one.setTitle("热度充值" + vipPackage.getTitle());
				one.setBuyType("User");
				one.setZsHot(vipPackage.getZsHot());
				one.setHot(vipPackage.getHot());
				one.setTime(0);
				one.setPrice(vipPackage.getPrice());
				price = vipPackage.getPrice();
				one.setStatus(2);
				one.setOrderType(2);
				one.setVipPackageId(vipPackage.getId());
				one.setCreateTime(SystemClock.now()/1000L);
				one.setUpdateTime(SystemClock.now()/1000L);
				if (user_id.longValue() == 140901L) {
					one.setPrice(new BigDecimal(0.01));
				}
				one.save();
		 }
		 String partner = WeiXinUtil.partner;
         String openId = CookiesUtil.getName(getRequest(), "wx_openid");
         String currTime = TenpayUtil.getCurrTime();
         //8位日期
         String strTime = currTime.substring(8, currTime.length());
         //四位随机数
         String strRandom = TenpayUtil.buildRandom(4) + "";
         //10位序列号,可以自行调整。
         String strReq = strTime + strRandom;
         //商户号
         String nonce_str = strReq;
         //商品描述根据情况修改
         String body = "五十度套餐充值";
         //商户订单号
         String out_trade_no = trade_no;
         //订单生成的机器 IP
         String spbill_create_ip = getRequest().getRemoteAddr();
         SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
         parameters.put("appid", WeiXinUtil.appid);
         parameters.put("attach", out_trade_no);
         parameters.put("body", body);
         parameters.put("mch_id", partner);
         parameters.put("nonce_str", nonce_str);
         parameters.put("notify_url", "http://api.50dufei.top/callback/wxpay");
         parameters.put("openid", openId);
         parameters.put("out_trade_no", out_trade_no);

         parameters.put("spbill_create_ip",spbill_create_ip);
         int total_fee = price.multiply(new BigDecimal(100)).intValue();
         parameters.put("total_fee", String.valueOf(total_fee));
         parameters.put("trade_type", "JSAPI");
         
         String sign = WeiXinUtil.createSign2("UTF-8", parameters);
         parameters.put("sign", sign);
         String requestXML = WeiXinUtil.getRequestXml(parameters);
         String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
         String prepay_id = new GetWxOrderno().getPayNo(createOrderURL,requestXML);  //CommonUtil.httpsRequest(createOrderURL, "POST", requestXML);
         SortedMap<String, String> finalpackage = new TreeMap<String, String>();
         String timestamp = Sha1Util.getTimeStamp();
         
         String packages = "prepay_id="+prepay_id;
         finalpackage.put("appId", WeiXinUtil.appid);
         finalpackage.put("timeStamp", timestamp);
         finalpackage.put("nonceStr", nonce_str);
         finalpackage.put("package", packages);
         finalpackage.put("signType", "MD5");
         String finalsign = WeiXinUtil.createSign3("UTF-8",finalpackage);
         setAttr("timestamp", timestamp);
         setAttr("nonceStr", nonce_str);
         setAttr("p", packages);
         setAttr("sign", finalsign);
         render("wx.html");
		}
	}
	
	public void success() {
		renderText("支付成功!");
	}
	
	
	/*
	  * 支付宝 
	  */
	public void alipay() {
		String user_name = getPara("user_name");
		Users users = Users.dao.findFirst("select id from users where user_mobile ='" + user_name + "'");
	    if( users == null){
	    	Long user_id = getParaToLong("user_name") - 20000000L;
	    	users = Users.dao.findById(user_id);
	    }
	    if(users == null) {
	    	setAttr("user_name", CookiesUtil.getName(getRequest(), "user_name"));
			List<VipPackage> package_list = VipPackage.dao.find("select * from vip_package where status = 1  order by id desc ");
			setAttr("package_list", package_list);
		    render("vip2.html");
		    return;
	    }
	    CookiesUtil.add(getResponse(), "user_name", user_name);
	    Long user_id = users.getId();
		String package_id = getPara("package_id");
		VipPackage vipPackage = VipPackage.dao.findById(package_id);
		String trade_no = Toolkit.newTradeNo();
		String subject = "";
		VipRecord one = null;
		if (vipPackage != null) {
			if (vipPackage.getType() == 1) {
				one = new VipRecord();
				one.setUserId(user_id.intValue());
				one.setOrderNum(trade_no);
				subject = vipPackage.getTitle();
				one.setTitle(vipPackage.getTitle());
				one.setBuyType("User");
				one.setZsHot(vipPackage.getZsHot());
				one.setTime(Integer.valueOf(vipPackage.getDays()));
				one.setPrice(vipPackage.getPrice());
				one.setStatus(2);
				one.setOrderType(1);
				one.setVipPackageId(vipPackage.getId());
				one.setCreateTime(SystemClock.now()/1000L);
				one.setUpdateTime(SystemClock.now()/1000L);
				if (user_id.longValue() == 140901L) {
					one.setPrice(new BigDecimal(0.01));
				}
				one.save();
			} else {
				one = new VipRecord();
				one.setUserId(user_id.intValue());
				one.setOrderNum(trade_no);
				subject = "热度充值" + vipPackage.getTitle();
				one.setTitle("热度充值" + vipPackage.getTitle());
				one.setBuyType("User");
				one.setZsHot(vipPackage.getZsHot());
				one.setHot(vipPackage.getHot());
				one.setTime(0);
				one.setPrice(vipPackage.getPrice());
				one.setStatus(2);
				one.setOrderType(2);
				one.setVipPackageId(vipPackage.getId());
				one.setCreateTime(SystemClock.now()/1000L);
				one.setUpdateTime(SystemClock.now()/1000L);
				if (user_id.longValue() == 140901L) {
					one.setPrice(new BigDecimal(0.01));
				}
				one.save();
		  }
		}
		//https://openapi.alipay.com/gateway.do
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id_51du, AlipayConfig.alipay_cm_private_key_51du, "json", "utf-8", AlipayConfig.alipay_app_public_key_51du, "RSA2");
		
//		AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl("http://api.50dufei.top/pay/success");
		alipayRequest.setNotifyUrl("http://api.50dufei.top/callback/alipay");
		try {
			//商户订单号，商户网站订单系统中唯一订单号，必填
//			String out_trade_no = new String(trade_no.getBytes("ISO-8859-1"),"UTF-8");
			//付款金额，必填
//			String total_amount = new String(String.valueOf(vipPackage.getPrice()).getBytes("ISO-8859-1"),"UTF-8");
			//订单名称，必填
//			 subject = new String(vipPackage.getTitle().getBytes("ISO-8859-1"),"UTF-8");
			//商品描述，可空
			alipayRequest.setBizContent("{\"out_trade_no\":\""+ trade_no +"\"," 
					+ "\"total_amount\":\""+ vipPackage.getPrice() +"\"," 
					+ "\"subject\":\""+ subject +"\"," 
//					+ "\"body\":\""+ body +"\"," 
					+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
			
			String result = alipayClient.pageExecute(alipayRequest).getBody();
			System.out.println(result);
			getResponse().setContentType("text/html;charset=utf-8");
			getResponse().getWriter().write(result);
			getResponse().getWriter().flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/*
	  * 支付宝 手机页面支付
	  */
	public void alipay2() {
		String user_name = getPara("user_name");
		Users users = Users.dao.findFirst("select id from users where user_mobile ='" + user_name + "'");
	    if( users == null){
	    	Long user_id = getParaToLong("user_name") - 20000000L;
	    	users = Users.dao.findById(user_id);
	    }
	    if(users == null) {
	    	setAttr("user_name", CookiesUtil.getName(getRequest(), "user_name"));
			List<VipPackage> package_list = VipPackage.dao.find("select * from vip_package where status = 1  order by id desc ");
			setAttr("package_list", package_list);
		    render("vip4.html");
		    return;
	    }
	    CookiesUtil.add(getResponse(), "user_name", user_name);
	    Long user_id = users.getId();
		String package_id = getPara("package_id");
		VipPackage vipPackage = VipPackage.dao.findById(package_id);
		String trade_no = Toolkit.newTradeNo();
		String subject = "";
		VipRecord one = null;
		if (vipPackage != null) {
			if (vipPackage.getType() == 1) {
				one = new VipRecord();
				one.setUserId(user_id.intValue());
				one.setOrderNum(trade_no);
				subject = vipPackage.getTitle();
				one.setTitle(vipPackage.getTitle());
				one.setBuyType("User");
				one.setZsHot(vipPackage.getZsHot());
				one.setTime(Integer.valueOf(vipPackage.getDays()));
				one.setPrice(vipPackage.getPrice());
				one.setStatus(2);
				one.setOrderType(1);
				one.setVipPackageId(vipPackage.getId());
				one.setCreateTime(SystemClock.now()/1000L);
				one.setUpdateTime(SystemClock.now()/1000L);
				if (user_id.longValue() == 140901L) {
					one.setPrice(new BigDecimal(0.01));
				}
				one.save();
			} else {
				one = new VipRecord();
				one.setUserId(user_id.intValue());
				one.setOrderNum(trade_no);
				subject = "热度充值" + vipPackage.getTitle();
				one.setTitle("热度充值" + vipPackage.getTitle());
				one.setBuyType("User");
				one.setZsHot(vipPackage.getZsHot());
				one.setHot(vipPackage.getHot());
				one.setTime(0);
				one.setPrice(vipPackage.getPrice());
				one.setStatus(2);
				one.setOrderType(2);
				one.setVipPackageId(vipPackage.getId());
				one.setCreateTime(SystemClock.now()/1000L);
				one.setUpdateTime(SystemClock.now()/1000L);
				if (user_id.longValue() == 140901L) {
					one.setPrice(new BigDecimal(0.01));
				}
				one.save();
		  }
		}
		//https://openapi.alipay.com/gateway.do
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id_51du, AlipayConfig.alipay_cm_private_key_51du, "json", "utf-8", AlipayConfig.alipay_app_public_key_51du, "RSA2");
		
		AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
//		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl("http://api.50dufei.top/pay/success");
		alipayRequest.setNotifyUrl("http://api.50dufei.top/callback/alipay");
		try {
			//商户订单号，商户网站订单系统中唯一订单号，必填
//			String out_trade_no = new String(trade_no.getBytes("ISO-8859-1"),"UTF-8");
			//付款金额，必填
//			String total_amount = new String(String.valueOf(vipPackage.getPrice()).getBytes("ISO-8859-1"),"UTF-8");
			//订单名称，必填
//			 subject = new String(vipPackage.getTitle().getBytes("ISO-8859-1"),"UTF-8");
			//商品描述，可空
			alipayRequest.setBizContent("{\"out_trade_no\":\""+ trade_no +"\"," 
					+ "\"total_amount\":\""+ vipPackage.getPrice() +"\"," 
					+ "\"subject\":\""+ subject +"\"," 
//					+ "\"body\":\""+ body +"\"," 
					+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
			
			String result = alipayClient.pageExecute(alipayRequest).getBody();
			getResponse().setContentType("text/html;charset=utf-8");
			getResponse().getWriter().write(result);
			getResponse().getWriter().flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
